import Request from 'luch-request'
// 设置请求地址前缀
import { APPINFO } from "@/config/baseUrl.js"
let apiPrefix = APPINFO.api_url
let apiPrefixDev = APPINFO.api_url_test;
const globalApi = (process.env.NODE_ENV === "development") ? apiPrefixDev : apiPrefix;

// 定义请求全局配置
const http = new Request({
  baseURL: globalApi, //设置请求的base url
  // #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
  timeout: 300000, //超时时长5分钟 H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)、微信小程序（2.10.0）、支付宝小程序
  // #endif
  header: {
    'Content-Type': 'application/json;charset=UTF-8;',
    "X-Requested-With": "XMLHttpRequest"
  }
});

//请求拦截器 - 可使用async await 做异步操作
http.interceptors.request.use((config) => {
  // 请求前挂上token
  const token = uni.getStorageSync('token');
  if (token) {
    config.header.Authorization = 'Bearer ' + token;
  }
  if (config.method === 'UPLOAD') {
    // #ifdef MP-ALIPAY
    config.fileType = 'image/video/audio';
    // #endif
  }
  uni.showNavigationBarLoading()
  return config
}, error => {
  return Promise.resolve(error)
})

//响应拦截器
http.interceptors.response.use((response) => {
  uni.hideNavigationBarLoading()
  // console.log(response)
  return response
}, (error) => {
  uni.hideNavigationBarLoading()
  let tip = '';
  switch (error.statusCode) {
    case 401:
      uni.removeStorageSync("token");
      uni.navigateTo({
        url: "/pages/login/authorize"
      })
      break;
    case 404:
      tip = "请求不存在"
      break;
    case 405:
      tip = "请求方式不正确"
      break;
    default:
      tip = "请求失败了"
      break;
  }
  uni.showToast({
    title: tip,
    icon: "none",
    duration: 1500
  });
  return Promise.resolve(error)
})

const request = (query = {}, url) => {
  // 整合传递参数
  let method = query.method || "GET"
  let data = query.data || {}
  let params = query.params || {}
  let formData = query.formData || {}
  let name = query.name || ''
  let filePath = query.filePath || ''
  // 所有请求方式的超集
  return http.middleware({
    method: method, // 请求方法必须大写 [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE|UPLOAD|DOWNLOAD]
    url: url,
    data: data,
    timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)、微信小程序（2.10.0）、支付宝小程序
    params: params,
    // #ifdef APP-PLUS
    firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
    // #endif
    // 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
    custom: {}, // 自定义参数
    formData: formData,
    name: name,
    filePath: filePath,
    // 返回当前请求的task, options。请勿在此处修改options。非必填
    getTask: (task, options) => {
      // setTimeout(() => {
      //   task.abort()
      // }, 500)
    },
    //validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示，非必填选项
    //	return statusCode >= 200 && statusCode < 300
    //}
  })
}
export default request;
